'''
Created on Mar 3, 2012

@author: oabalbin
'''
'''
Created on Mar 27, 2011

@author: oabalbin
'''
import logging
import argparse
from collections import deque

def list_of_names(inputfile, pfield):
    
    genlist=deque()
    for line in inputfile:
        if line.startswith('#'):
            continue
        fields = line.strip('\n').split('\t')
        genlist.append(fields[pfield])
    return genlist


def create_exons_bedfile(cfile, ofile, genelist, ucsc):
    '''
    Header of the cfile
    #name   chrom   strand  txStart txEnd   cdsStart        
    cdsEnd  exonCount       exonStarts      exonEnds        
    name2   score   name2   cdsStartStat    cdsEndStat      exonFrames
    '''
    hddict={'#name':0,'chrom':1,'strand':2,'txStart':3,'txEnd':4,'cdsStart':5,
            'cdsEnd':6,'exonCount':7,'exonStarts':8,'exonEnds':9,'name2':10,'score':11,
            'cdsStartStat':12,'cdsEndStat':13,'exonFrames':14}
    ifile = open(cfile)
    hd = ifile.next()
    of=open(ofile,'w')

    for l in ifile:
        f=l.strip('\n').split('\t')
        if (len(f[hddict['chrom']].split('_')) < 2) and \
           (f[hddict['name2']] in genelist):
            
            exonstarts=f[hddict['exonStarts']].split(',')
            exonends=f[hddict['exonEnds']].split(',')
            exonstarts.pop(),exonends.pop() # Particularity of this file. the last exon also have (,) xx,
            i=0
            if not ucsc:
                CHRM = f[hddict['chrom']].strip('chr')
            else:
                CHRM = f[hddict['chrom']]
            
            for es, ee in zip(exonstarts,exonends):
                name= '%s|E%d|%s'%(f[hddict['name2']],i,f[hddict['#name']])
                
                ol = [CHRM, es, ee, name, f[hddict['score']],f[hddict['strand']] ]
                of.write(",".join(ol).replace(',','\t')+'\n')
                i+=1
    ifile.close()
    of.close()
    

def main():
    logging.basicConfig(level=logging.DEBUG,
                        format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    parser = argparse.ArgumentParser()
    parser.add_argument("--knownGenes", dest="knownGenes", 
                        default="/exds/users/oabalbin/sw/vcfCodingSnps.v1.5/geneLists/refGene.B37.txt")
    parser.add_argument("--genelist", dest="genelist", 
                        default="/exds/users/oabalbin/projects/exomes/genelists/actionable_gene_list_06_27_11.txt")
    parser.add_argument("--UCSC", dest="UCSC",action="store_true",default=False)
    
    options = parser.parse_args()
    ofile = options.genelist+'_ensemble_exones.bed'
    return create_exons_bedfile(options.knownGenes, ofile, 
                                list_of_names(open(options.genelist),0),options.UCSC
                                )
            
if __name__ == '__main__':     
    import sys
    sys.exit(main())

